<template>
  <a-spin class="table-gl-con" :loading="submitLoading">
    <TableWrap style="flex: 1" @refresh="getTableList">
      <template #headerLeft>
        <a-space>
          <p>共计 {{ total }} 条</p>
          <a-button class="gray-outline" size="medium" @click="openHandleDialog">风险处理</a-button>
          <p style="font-size: 12px; color: #999">取近60天的广告指标作为风险判断标准</p>
        </a-space>
      </template>
      <template #tableBody>
        <a-table
          class="table-singe-line"
          ref="tableRef"
          row-key="id"
          :loading="tableLoading"
          @selection-change="selectColumn"
          :row-selection="rowSelection"
          :bordered="false"
          :data="tableList"
          :scroll="{
            x: 2250,
            y: '100%',
          }"
          size="mini"
          @sorter-change="sorterChange"
          :pagination="false"
        >
          <template #columns>
            <a-table-column :width="180" title="广告活动" fixed="left">
              <template #cell="{ record }">
                <div class="flex">
                  <div class="ad-type-tag">{{ AdTypesTag[record.adType] }}</div>
                  <a-popover :content="record.campaignName" position="bottom">
                    <p @click="openCampaignDetail(record, '指标趋势')" class="highlight cursor text-limit-two">{{ record.campaignName }}</p>
                  </a-popover>
                </div>
              </template>
            </a-table-column>
            <a-table-column :width="120" title="店铺" fixed="left" data-index="shopName">
              <template #cell="{ record }">
                <a-popover :content="record.shopName" position="bottom">
                  <p class="text-limit-two">{{ record.shopName }}</p>
                </a-popover>
              </template>
            </a-table-column>
            <a-table-column data-index="portfolioName" :width="120" title="广告组合" />
            <a-table-column :width="70" title="销售员" data-index="operationsName" />
            <a-table-column :width="220" title="风险类型" data-index="riskType">
              <template #title>
                <a-popover>
                  <template #content>
                    <p>满足以下所有条件的，则被判定为风险广告</p>
                    <p>低转化：曝光小于等于 300 或 点击小于等于 30 </p>
                    <p>低产出：acos大于等于30且roas小于等于 1</p>
                    <p>有广告花费：广告花费大于 0</p>
                  </template>
                  <p>
                    <span>风险类型</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <a-space wrap :size="4">
                  <a-tag style="margin: 2px 0" v-for="(riskType, i) of record.riskType ? record.riskType.split(',') : []" size="small" :key="i" color="orangered" bordered>{{ riskType }}</a-tag>
                </a-space>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="投放类型" data-index="targetingType" />
            <a-table-column :width="80" title="每日预算">
              <template #cell="{ record }">
                <div class="flex-c">
                  <p>
                    <span>{{ getCurrencySymbol(record.marketplaceId) }}</span>
                    <span>{{ Number(record.budgetAmount || 0).toFixed(2) }}</span>
                  </p>
                </div>
              </template>
            </a-table-column>
            <a-table-column :width="90" title="开始日期" :sortable="sortable" data-index="startDate" />
            <a-table-column :width="100" title="近14天利润" :sortable="sortable" data-index="attributedSaleProfit14d">
              <template #cell="{ record }">
                <p v-if="record.attributedSaleProfit14d || record.attributedSaleProfit14d === 0">{{ Number(record.attributedSaleProfit14d).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="impressions">
              <template #title>
                <a-popover content="广告曝光次数">
                  <p>
                    <span>曝光量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="clicks">
              <template #title>
                <a-popover content="广告点击次数">
                  <p>
                    <span>点击量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CTR" :sortable="sortable" align="right" data-index="ctr">
              <template #title>
                <a-popover content="广告点击转化率=点击量/曝光量">
                  <p>
                    <span>CTR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="90" title="花费" align="right" :sortable="sortable" data-index="cost">
              <template #title>
                <a-popover content="亚马逊广告花费">
                  <p>
                    <span>花费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cost || record.cost === 0">${{ Number(record.cost).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPC" align="right" :sortable="sortable" data-index="cpc">
              <template #title>
                <a-popover content="单次点击成本，CPC=广告花费/点击量">
                  <p>
                    <span>CPC</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CVR" align="right" :sortable="sortable" data-index="cvr">
              <template #title>
                <a-popover content="广告转化率，CVR=广告订单量/点击量*100%">
                  <p>
                    <span>CVR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPA" align="right" :sortable="sortable" data-index="cpa">
              <template #title>
                <a-popover content="单笔订单平均广告花费，CPA=广告花费/广告订单量">
                  <p>
                    <span>CPA</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpa || record.cpa === 0">${{ Number(record.cpa).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="总单量" :sortable="sortable" align="right" data-index="purchasesOrder">
              <template #title>
                <a-popover content="广告带来的订单及关联订单数量">
                  <p>
                    <span>总单量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesOrder || record.purchasesOrder === 0">{{ record.purchasesOrder }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="商品销量" :sortable="sortable" align="right" data-index="purchasesSale">
              <template #title>
                <a-popover content="广告商品销量">
                  <p>
                    <span>商品销量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="销售额" align="right" :sortable="sortable" data-index="saleAmount">
              <template #title>
                <a-popover content="广告带来的销售额及关联销售额">
                  <p>
                    <span>销售额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ACOS" :sortable="sortable" align="right" data-index="acos">
              <template #title>
                <a-popover content="投入产出比，ACOS=广告花费/广告销售额*100%">
                  <p>
                    <span>ACOS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.acos || record.acos === 0">{{ Number(record.acos).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ROAS" :sortable="sortable" align="right" data-index="roas">
              <template #title>
                <a-popover content="支出回报，ROAS=广告销售额/广告花费">
                  <p>
                    <span>ROAS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.roas || record.roas === 0">{{ Number(record.roas).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column title="风险处理方式" :width="140" fixed="right">
              <template #cell="{ record }">
                <div class="flex-c-sb">
                  <p class="highlight cursor" @click.stop="openCampaignDetail(record, '处理日志')">
                    <span>{{ OperationsType[record.operationsType] || record.operationsType || '--' }}</span>
                    <span v-if="record.operationsType == 'ADJUST'">：{{ getOperationsAdjustDetail(record) }}</span>
                  </p>
                  <icon-edit class="highlight cursor" @click.stop="openCampaignDetail(record, '风险处理')" />
                </div>
              </template>
            </a-table-column>
            <a-table-column title="近7天操作时间" :width="140" data-index="lastUpdateDateTime" :sortable="sortable" fixed="right">
              <template #cell="{ record }">
                <p class="highlight cursor" @click="openCampaignDetail(record, '操作日志')">{{ $setTime(record.lastUpdateDateTime) }}</p>
              </template>
            </a-table-column>
            <a-table-column title="意见留言" :width="70" fixed="right">
              <template #cell="{ record }">
                <div class="flex-c cursor highlight" @click="openCampaignDetail(record, '留言')">
                  <icon-message size="16" style="margin-right: 2px" />
                  <span>{{ record.commentNum > 99 ? '99+' : record.commentNum }}</span>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="80" fixed="right" #cell="{ record }">
              <a-button type="text" @click="showAdjustAdver(record)">调整广告</a-button>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-spin>
  <!-- pl风险处理 -->
  <a-modal :width="600" v-model:visible="showHandleDialog" :footer="false" title="风险处理-批量" title-align="start" :mask-closable="false">
    <HandleRisk v-if="showHandleDialog" :adList="selectRows" @cancel="showHandleDialog = false" @success="handleSuccess" />
  </a-modal>
  <!-- 编辑广告活动 -->
  <EditCampaign v-if="showEditDialog" :isShow="showEditDialog" :shop="shopInfo" :currentItem="currentData" @closed="showEditDialog = false" @success="getTableList" />
  <!-- 详情 -->
  <RiskDetail showType="campaign" v-if="showDetail" :tabName="detailType" :currentData="currentData" :isShow="showDetail" @closed="showDetail = false" @update="getTableList" />
  <!-- 调整广告 -->
  <adjustAdver v-model="showAdjustAdverModal" v-if="showAdjustAdverModal" :info="currentData" />
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { riskPageList } from '@/api/advert'
  import RiskDetail from './riskDetail.vue'
  import EditCampaign from './editCampaign.vue'
  import HandleRisk from './handleRisk.vue'
  import { Message } from '@arco-design/web-vue'
  import { OperationsType, AdTypesTag, OperationsAdjustDetailType } from '../../types'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  import adjustAdver from './adjustAdver/adjustAdver.vue'
  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
    markedtList: {
      type: Array,
      default: () => [],
    },
    shopList: {
      type: Array,
      default: () => [],
    },
    userList: {
      type: Array,
      default: () => [],
    },
    type: {
      type: Number,
      default: 0,
    },
  })
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const tableListMap = ref({})
  const showDetail = ref(false)
  const showEditDialog = ref(false)
  const submitLoading = ref(false)
  const showHandleDialog = ref(false)
  const showAdjustAdverModal = ref(false)
  const currentData = ref<any>({})
  const shopInfo = ref<any>({})
  const selectRows = ref<any>([])
  const detailType = ref('')
  const tableRef = ref()

  const selectColumn = (val: any) => {
    selectIds.value = val
  }
  // 显示货币符号
  function getCurrencySymbol(marketplaceId: any) {
    let currency = marketPlaceList[marketplaceId]?.currency
    return currencySymbol[currency]
  }
  // 广告调整明细显示
  function getOperationsAdjustDetail(row: any) {
    row.operationsAdjustDetail
    let arr = row.operationsAdjustDetail?.split(',') || []
    let newArr = arr.map((val: string) => {
      return OperationsAdjustDetailType[val] || 'val'
    })
    return newArr.join(',')
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function getTableListByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 打开批量处理风险广告
  function openHandleDialog() {
    if (!selectIds.value.length) {
      return Message.error('请选择广告活动')
    }
    getSelectRows()
    showHandleDialog.value = true
  }
  // 风险处理成功
  function handleSuccess() {
    showHandleDialog.value = false
    getTableList()
  }

  // 获取列表数据
  async function getTableList() {
    tableLoading.value = true
    const res: any = await riskPageList({
      ...props.searchParams,
      ...searchVal.value,
      isQueryBurial: props.type,
    })
    tableLoading.value = false
    tableRef.value.selectAll(false)
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      el.id = el.shopId + el.campaignId + el.resourceId
      tableListMap.value[el.id] = el
    })
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.orderItems = null
    } else {
      searchVal.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }

  // 打开广告详情
  function openCampaignDetail(row: any, type: string) {
    currentData.value = row
    detailType.value = type
    showDetail.value = true
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }

  function showAdjustAdver(data: any) {
    currentData.value = data
    showAdjustAdverModal.value = true
  }

  defineExpose({ getTableListByVal })
</script>
<style lang="less" scoped>
  .ad-type-tag {
    font-size: 12px;
    color: #fff;
    flex-shrink: 0;
    padding: 2px 4px;
    line-height: 12px;
    transform: scale(0.75);
    height: 16px;
    margin-right: 2px;
    background-color: rgb(var(--primary-4));
  }
  .table-gl-con {
    height: 100%;
  }
  .gray {
    color: #999;
  }
  .normal {
    color: var(--color-text-2);
  }
  .success {
    color: rgb(var(--success-5));
  }
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
  .popconfirm-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
  .name-w {
    position: relativ;
    width: 100%;
    .more-edit {
      margin-left: 4px;
      font-size: 16px;
    }
  }
</style>
